package com.xieyingwangluo.yxpart.ehcache.server.impl;

import com.xieyingwangluo.yxpart.ehcache.server.UserCache;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: wangchaonan
 * @Date: 2018/9/30 10:36
 * @Version 1.0
 */
@Component
public class UserCacheImpl implements UserCache {
    @Resource
    private CacheManager cacheManager;

    @Override
    public boolean get(String tel) {
        Cache userCache = cacheManager.getCache("userCache");
        String user = userCache.get(tel, String.class);
        if (user == null) {
            return false;
        }
        return true;
    }

    @Override
    public boolean put(String tel) {
        Cache countCache = cacheManager.getCache("countCache");
        Integer count = countCache.get(tel, Integer.class);
        if (count != null) {
            if (count == 4) {
                Cache userCache = cacheManager.getCache("userCache");
                userCache.put(tel, "look");
                countCache.evict(tel);//重计数缓存移除当前用户计数
                return true;
            } else {
                countCache.put(tel, ++count);
            }
        } else {
            countCache.put(tel, 1);
        }
        return false;
    }
}
